//+build debug

package config

import (
	"bufio"
	"gopkg.in/yaml.v2"
	"io"
	"io/ioutil"
	"matrix/log"
	"os"
	"strings"
)

type DockerParam struct {
	Image       string
	Environment []string
	Env_file    []string
}

var YMLConfig struct {
	Version  string
	Services map[string]*DockerParam
}

var LoadEnvironment = func(key string) string {
	return currEnvironment[key]
}

//var IntranetIp string
var currEnvironment map[string]string

func SetPath(path string, cfgName string) {
	currEnvironment = make(map[string]string)
	YMLConfig.Services = make(map[string]*DockerParam)

	data, err := ioutil.ReadFile(path)
	if err != nil {
		log.Fatal("SetPath err: %v", err)
	}
	log.Debug("yml data:%v", string(data))
	err = yaml.Unmarshal(data, &YMLConfig)
	if err != nil {
		log.Fatal("SetPath unmarshal err: %v", err)
	}

	if tmp, ok := YMLConfig.Services[cfgName]; ok {
		log.Debug("cfg: %v, %+v", cfgName, tmp)
		for _, v := range tmp.Env_file {
			loadEnvFile(v)
		}
		for _, v := range tmp.Environment {
			if split := strings.Split(v, "="); len(split) == 2 {
				currEnvironment[split[0]] = split[1]
			}
		}
	}

	log.Debug("cfgName: %s", cfgName)
	for k, v := range currEnvironment {
		log.Debug("    %v: %v", k, v)
	}
}

func loadEnvFile(file string) {
	f, err := os.Open(file)
	log.Debug("load env file: %v", file)
	if err != nil {
		log.Error("loadEnvFile :%v, failed:%v", file, err)
		return
	}
	defer f.Close()

	rd := bufio.NewReader(f)
	for {
		line, err := rd.ReadString('\n') //以'\n'为结束符读入一行
		if len(line) > 0 {
			// 只替换第一个 =
			line = strings.Replace(line, "=", " ", 1)
			fields := strings.Fields(line)
			if len(fields) == 2 {
				currEnvironment[fields[0]] = fields[1]
			}
		}
		// log.Debug("%v", line)
		if err != nil || io.EOF == err {
			break
		}
	}
}
